﻿using System;
using ilanver.Data.NHibernate.Statics;

namespace ilanver.Data.NHibernate.Attributes
{
    [AttributeUsage(AttributeTargets.Class)]
    public class SessionFactoryAttribute : Attribute
    {
        public readonly string FactoryKey;

        public SessionFactoryAttribute(string factorKey)
        {
            FactoryKey = factorKey;
        }

        public static string GetKeyFrom(object anObject)
        {
            if (!NHibernateSession.IsConfiguredForMultipleDatabases())
                return NHibernateSession.DefaultFactoryKey;

            Type objectType = anObject.GetType();

            object[] attributes = objectType.GetCustomAttributes(typeof(SessionFactoryAttribute), true);

            if (attributes.Length > 0)
            {
                SessionFactoryAttribute attribute = (SessionFactoryAttribute)attributes[0];
                return attribute.FactoryKey;
            }

            return NHibernateSession.DefaultFactoryKey;
        }
    }
}
